package com.itistimetothink.cjetso;

import java.util.List;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import com.itistimetothink.cjetso.utilities.ARData;
import com.itistimetothink.cjetso.utilities.Marker;
import com.itistimetothink.cjetso.utilities.SensorsActivity;
import com.itistimetothink.networkdata.MyNetworkDataSource;
import com.itistimetothink.networkdata.NetworkDataSource;

public class MainActivity extends SensorsActivity {
	private static final String fb_id = "416965195026704";
	private Facebook facebook = new Facebook(fb_id);
	private static String user_id = null;
	private SharedPreferences mPrefs;
	
	private static final String DEFAULT_PIC = "http://www.cjetso.com/shop_images/cjetso_image.png";
	private static final String TAG = "MainActivity Debugging";
	static boolean downloadSuccessfully = true;
	private static final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
			1);
	private static final ThreadPoolExecutor exeService = new ThreadPoolExecutor(
			1, 1, 20, TimeUnit.SECONDS, queue);
	private static final Map<String, NetworkDataSource> sources = new ConcurrentHashMap<String, NetworkDataSource>();
	// ProgressDialog dialog = new ProgressDialog(this);
	private Button see_food, see_shop, see_leisure;
	static ProgressDialog dialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int width = displaymetrics.widthPixels;
		int height = displaymetrics.heightPixels;
		see_food = (Button) findViewById(R.id.see_food);
		see_shop = (Button) findViewById(R.id.see_shop);
		see_leisure = (Button) findViewById(R.id.see_leisure);
		
		mPrefs = getSharedPreferences("facebook_session", MODE_PRIVATE);	
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		user_id = mPrefs.getString("user_id", null);
		//Log.i("Check id", "ID CHECKING :" + user_id);
		if (access_token != null) {
			facebook.setAccessToken(access_token);
			//Log.i("Check id", "ID access_token :" + access_token);
		}
		if (expires != 0) {
			facebook.setAccessExpires(expires);
			//Log.i("Check id", "ID expires :" + expires);
		}
		
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(0, height/5, 0, 0);
		lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
		see_food.setLayoutParams(lp);
		see_food.setHeight(height/5);
		see_food.setWidth(width*3/5);
		
		see_shop.setHeight(height/5);
		see_shop.setWidth(width*3/5);
		
		see_leisure.setHeight(height/5);
		see_leisure.setWidth(width*3/5);
        NetworkDataSource placeInformation = new MyNetworkDataSource(this.getResources());
        sources.put("placeInformation",placeInformation);
		dialog = ProgressDialog.show(this, "Initializing",
				"CJetso, see Jetso", true, false);
		


	}
	@Override
	public void onResume(){
		super.onResume();
		Location last = ARData.getCurrentLocation();
		updateData(last.getLatitude(), last.getLongitude(), last.getAltitude());

	}

	public void SeeFood(View v) {
		Bundle bundle = new Bundle();
		bundle.putString("category", "food");
		bundle.putBoolean("downloadSuccessfully", downloadSuccessfully);
		ARData.setType("restaurant");
		Intent myIntent = new Intent(this, AugmentedMain.class);
		myIntent.putExtras(bundle);
		startActivity(myIntent);
	}

	public void SeeShop(View v) {
		Bundle bundle = new Bundle();
		bundle.putString("category", "shop");
		bundle.putBoolean("downloadSuccessfully", downloadSuccessfully);
		ARData.setType("fashion");
		Intent myIntent = new Intent(this, AugmentedMain.class);
		myIntent.putExtras(bundle);
		startActivity(myIntent);
	}

	public void SeeLeisure(View v) {
		Bundle bundle = new Bundle();
		ARData.setType("public");
		bundle.putBoolean("downloadSuccessfully", downloadSuccessfully);
		bundle.putString("category", "leisure");
		Intent myIntent = new Intent(this, AugmentedMain.class);
		myIntent.putExtras(bundle);
		startActivity(myIntent);
	}

	@Override
	public void onStart() {
        Log.i(TAG, "Main onStart");
		super.onStart();
	}

	@Override
	public void onLocationChanged(Location location) {
		super.onLocationChanged(location);
		updateData(location.getLatitude(), location.getLongitude(),
				location.getAltitude());
		Log.i(TAG, "onLocationChanged");

	}

	private void updateData(final double lat, final double lon, final double alt) {
		try {
	        Log.i(TAG, "Main updateData");
			exeService.execute(new Runnable() {

				public void run() {
					for (NetworkDataSource source : sources.values())
						download(source, lat, lon);
				}
			});
		} catch (RejectedExecutionException rej) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			Log.i(TAG, "Not running new download Runnable, queue is full.");
		} catch (Exception e) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			Log.i(TAG, "Exception running download Runnable.", e);
		}


	}

	private static boolean download(NetworkDataSource source, double lat,
			double lon) {
		if (source == null)
			return false;
		
        Log.i(TAG, "download updateData");
		String url = null;
		try {
			// TODO change needed
			url = source.createRequestURL(lat, lon);
		} catch (NullPointerException e) {
			return false;
		}

		List<Marker> markers = null;
		try {
			downloadSuccessfully = true;
			markers = source.parse(url);
		} catch (NullPointerException e) {
			if (dialog.isShowing()) {
				dialog.dismiss();
		        Log.i(TAG, "dialog.dismiss() updateData");
			}
			downloadSuccessfully = false;
			return false;
		}
		if (dialog.isShowing()) {
			dialog.dismiss();
	        Log.i(TAG, "dialog.dismiss() updateData");
		}
		ARData.addMarkers(markers);
        Log.i(TAG, "addMarkers updateData");

		return true;
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(Menu.NONE, Menu.FIRST + 1, 5, "Like CJETSO").setIcon(
				R.drawable.like_menu);
		menu.add(Menu.NONE, Menu.FIRST + 2, 5, "Share CJETSO").setIcon(
				R.drawable.share_menu);

		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			String likeLink="http://m.facebook.com/pages/Cjetso/135299383293727?ref=ts&fref=ts";
			// Intent i = new Intent(this, Preferences.class);
			Intent browserIntent2 = new Intent(Intent.ACTION_VIEW,
					Uri.parse(likeLink));
			startActivity(browserIntent2);
			break;

		case Menu.FIRST + 2:
			// Intent i = new Intent(this, Preferences.class);
			postCjetsoToWall();
			break;
		}
		return false;

	}
	
	public void postCjetsoToWall(){
		Bundle parameters = new Bundle();
		String link = "http://www.cjetso.com";
		String title = getString(R.string.cjetso_slogan);
		parameters.putString("message", title);
		//parameters.putString("link", title);
		Log.i("WAll ","description = "+title);
		parameters.putString("description", title+": "+link);
		parameters.putString("picture", DEFAULT_PIC);


		if (facebook.isSessionValid()) {
			Log.i("postToWall", "mFacebook.isSessionValid()");
			// mAsyncRunner.request("me/feed", parameters, "POST", new
			// FacebookPostListener(), null);

			facebook.dialog(this, "feed", parameters, new DialogListener() {
				@Override
				public void onFacebookError(FacebookError e) {
					Log.i("onFacebookError", "youtubeLink == " + e);
				}

				@Override
				public void onError(DialogError e) {
					Log.i("onFacebookError", "onCancel == " + e);
				}

				@Override
				public void onComplete(Bundle values) {
				}

				@Override
				public void onCancel() {
				}
			});

		} else {
			Log.i("postToWall",
					"mFacebook.getAccessToken(): " + facebook.getAccessToken());

			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {
						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							Log.i("postToWall", "mFacebook.onComplete(): ");

							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error
							Log.i("postToWall", "mFacebook.onError(): " + error);

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors
							Log.i("postToWall", "mFacebook.onFacebookError(): "
									+ fberror);
						}

					});
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
		// Log.v("onActivityResult", "no pref");

	}

}
